package utils

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"go-project/common"
	"strconv"
	"time"
)

func GenerateToken(userId uint, username string) (string, error) {
	claims := jwt.MapClaims{}
	claims["authorized"] = true
	claims["userId"] = userId
	claims["username"] = username
	claims["exp"] = time.Now().Add(time.Second * time.Duration(common.CONFIG.JWT.TTL)).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(common.CONFIG.JWT.Signed))
}

// ExtractTokenID 从jwt中解析出user
func ExtractTokenID(c *gin.Context) (uint, string, error) {
	tokenStr := c.GetHeader("token")
	if len(tokenStr) == 0 {
		return 0, "", fmt.Errorf("未发现有效token")
	}
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (any, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(common.CONFIG.JWT.Signed), nil
	})
	if err != nil {
		return 0, "", fmt.Errorf("token解析错误")
	}
	claims, ok := token.Claims.(jwt.MapClaims)
	// 如果jwt有效，将user_id转换为浮点数字符串，然后再转换为 uint32
	if ok && token.Valid {
		uid, err := strconv.ParseUint(fmt.Sprintf("%.0f", claims["userId"]), 10, 32)
		if err != nil {
			return 0, "", err
		}
		return uint(uid), claims["username"].(string), nil
	}
	return 0, "", nil
}
